﻿using Ay.Framework.WPF.Controls;
using MPSystem.Models;
using Base.BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;
using Ay.Framework.WPF;
using MPSystem.Views.YFQ;
using System.IO;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage_Freq : Page
    {
        Common common = new Common();
        public static ZCYLPage_Freq Me = null;
        public static int cqbh=0,gzmbh = 0;
        private List<double> P1 = new List<double>() { 10, 34.6, 60, 80 };
        private List<double> P2 = new List<double>() { 11, 54, 70, 80 };
        private List<double> P3 = new List<double>() { 13, 45, 70, 90 };
        private List<string> test = new List<string>() { "正常", "正常1", "正常1", "正常2" };
        private List<double> P12 = new List<double>();
        private List<string> S = new List<string>() { "正常" };
        private List<double> F1 = new List<double>();
        private List<double> F2 = new List<double>();
        private List<double> F3 = new List<double>();
        private List<double> F12 = new List<double>();
        private List<double> Freq = new List<double>();
        private List<DateTime> T = new List<DateTime>();
        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set {  _IsBusy=value ; }
        }
        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private string ComanpyName = "";
        private bool FirstReflash = true;
        
        private string dtStart = "", dtEnd = "", wz = "", hSpan = "", MPa = "",sfzj="0", SYZT="" ;
        int bh = 0;
        string DW = "MPa";
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();

        public ZCYLPage_Freq()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;

            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //工作面
            var rgzm = ConfigService.GetGZM(rcq.ElementAt(0).CQBH);
            combgzm.ItemsSource = common.LoadCombox_IECobx(rgzm);
            if (rgzm.Count() > 0) combgzm.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompanyName.Text = ComanpyName + "综采支架载荷频度分析统计图";

        }

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //SycnReflash();
        }
        

        /// <summary>
        /// 后台加载
        /// </summary>
        void SycnReflash()
        {
            var cond = DataQuery_ZCZJFH_Conditon.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                {
                    bh = int.Parse(cond["bh"]);
                    wz = cond["wz"];
                    sfzj = cond["sfzj"];//是否整架
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    DataZcService ds = new DataZcService();
                    int cq = 0, gzm = 0;//测区，工作面
                    try
                    {
                        cq = int.Parse(combcq.SelectedValue.ToString());
                        gzm = int.Parse(combgzm.SelectedValue.ToString());
                    }
                    catch
                    {
                    } 
                 
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd) + new TimeSpan(23, 59, 59);
                    int channel = AyCommon.ToInt(sfzj);
                    var r = ds.CurveFreq(cq,gzm, bh,wz, db, de, channel);
                    CreateChartColumn("支架载荷频度", r, channel);
                });
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin.IsBusy = true;
            worker.RunWorkerAsync();
        }

        public void CreateChartColumn(string name, CurveZc zc,int channel)
        {
            //创建一个图标
            // Chart chart = new Chart();
            this.chart.Series.Clear();
            if (FirstReflash)
            {
                //设置图标的宽度和高度
                //chart.Width = 580;
                //chart.Height = 380;
 
                //是否启用打印和保持图片
                chart.ToolBarEnabled = true;

                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示

                //创建一个标题的对象
                Title title = new Title();

                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);

                //向图标添加标题
                chart.Titles.Add(title);
                Axis axisX = new Axis();
                chart.AxesX.Add(axisX);
                Axis axisY1 = new Axis();

                axisY1.AxisType = AxisTypes.Primary;
                Axis yAxis = new Axis();
                axisY1.Title = "";
                //设置图标中Y轴的最小值永远为0           
                yAxis.AxisMinimum = 0;
                //设置图表中Y轴的后缀          
                yAxis.Suffix = "";
                chart.AxesY.Add(yAxis);
                FirstReflash = false;
            }

            //创建第一个DataSeries
            List<double> valuey = zc.Freq;
            DataSeries oneDataSeries = new DataSeries();
            oneDataSeries.LabelEnabled = true;
            oneDataSeries.ShowInLegend = ck.IsChecked == true;   
            oneDataSeries.RenderAs = ck.IsChecked==true?RenderAs.Pie: RenderAs.Column;
            oneDataSeries.MarkerEnabled = true;
            oneDataSeries.YValueFormatString = "0.00'%'";
            DataPoint oneDataPoint = null;
            string lastLabel = "0";
            for (int i = 0; i < valuey.Count; i++)
            {
                oneDataPoint = new DataPoint();
                oneDataPoint.AxisXLabel = lastLabel+"-"+zc.X[i];
                oneDataPoint.YValue = valuey[i];
                oneDataPoint.ToolTipText = string.Format("{0} {1:f2}%", oneDataPoint.AxisXLabel, valuey[i]);
                lastLabel = zc.X[i];
                oneDataSeries.DataPoints.Add(oneDataPoint);
            }
            chart.Series.Add(oneDataSeries);
        }

        /// <summary>
        /// 获取随机颜色
        /// </summary>
        Random random = new Random();
        public System.Windows.Media.Color GetRandomColor()
        {
          return Color.FromRgb((byte)random.Next(0, 255), (byte)random.Next(0, 255), (byte)random.Next(0, 255));
        }

        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            //DataQuery_ZCZJFH_Conditon.Me.LoadBH();
            SycnReflash();
        }

        /// <summary>
        /// 高级查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnH_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--附加信息", "/Views/YFQ/DataQuery_ZCZJFH_Conditon.xaml", 600, 500);
        }

        private void Combgzm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combgzm.SelectedValue != null)
            {
                gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            }
        }

        private void Chart_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!MPSystem.SESSIONS.ShowMenu || chart.Series.IsEmpty() || chart.Series[0].DataPoints.Count == 0)
            {
                return;
            }
            ContextMenu menu = new ContextMenu();
            MenuItem menuItem3 = new MenuItem();
            menuItem3.Header = "导出所有";
            menuItem3.Click += new RoutedEventHandler((s, ee) => {

                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = ".txt";
                dlg.Filter = "txt file|*.txt";
                dlg.CheckFileExists = false;
                if (dlg.ShowDialog() == true)
                {
                    FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.NewLine = Environment.NewLine;
                    foreach (var dp in chart.Series[0].DataPoints)
                    {
                        sw.WriteLine(string.Format("{0} {1:f2}%", dp.AxisXLabel, dp.YValue));
                    }
                    sw.Flush();
                    sw.Close();
                    AyMessageBox.Show("导出完毕！");
                }
            });
            menu.Items.Add(menuItem3);
            chart.ContextMenu = menu;
        }

        /// <summary>
        /// 附加信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAttac_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("检测报表--附加信息", "/Views/YFQ/ZCYLPage_Attac.xaml", 600, 500);
        }
        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                DataQuery_ZCZJFH_Conditon.Me.LoadBH();
            }
            window.ShowDialog();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            DataQuery_ZCZJFH_Conditon.Me.UpdateCond();
            window.Hide();
            Me.SycnReflash();
            e.Cancel = true;
        }


        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var gzmSource = ConfigService.GetGZM(cqbh);
            combgzm.ItemsSource = common.LoadCombox_IECobx(gzmSource);
            if (gzmSource.Count() > 0) combgzm.SelectedIndex = 1;
        }

        private void ck_Checked(object sender, RoutedEventArgs e)
        {
            if (combcq.SelectedValue!=null && combgzm.SelectedValue!=null &&cqbh > 0 && gzmbh > 0)
            {
                SycnReflash();
            }
        }

        private void ck_Unchecked(object sender, RoutedEventArgs e)
        {
            if (combcq.SelectedValue != null && combgzm.SelectedValue != null && cqbh > 0 && gzmbh > 0)
            {
                SycnReflash();
            }
        }
    }
}
